package com.micro.demo.controller;

import com.micro.demo.entities.Dept;
import com.micro.demo.service.DeptService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@RestController
public class DeptController {
    @Autowired
    private DeptService service;

    @RequestMapping(value = "/dept/add", method = RequestMethod.POST)
    public boolean add(@RequestBody Dept dept) {
        return service.add(dept);
    }

    @RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
    @HystrixCommand(fallbackMethod = "processHystrix_Get")
    public Dept get(@PathVariable("id") Long id) {
        Dept dept = service.get(id);
        if (null == dept) {
            throw new RuntimeException("该ID：" + id + "没有没有对应的信息");
        }

        return dept;
    }

    public Dept processHystrix_Get(@PathVariable("id") Long id) {
        return new Dept().setDeptno(id)
                .setDname("该ID：" + id + "没有没有对应的信息,null--@HystrixCommand")
                .setDb_source("no this database in MySQL");
    }


    int i=0;

    @RequestMapping(value = "/dept/list", method = RequestMethod.GET)
    @HystrixCommand(fallbackMethod = "processHystrix_List")
    public List<Dept> list() {
        i++;
        if (i % 2==0) {
            throw new RuntimeException("突发异常：" + i + "没有没有对应的信息");
        }
        return service.list();
    }
    public List<Dept> processHystrix_List() {
        List<Dept> list = new ArrayList<>();
        list.add(processHystrix_Get(null) );
        return list;
    }


}